﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Kristall.Engine;
using Kristall.Engine.Behaviors;

namespace Kristall.MyGame.Behaviors
{
    public class PatrolBehavior : Behavior
    {
        Vector2 _direction = Vector2.UnitX;

        public PatrolBehavior(NPC npc)
            : base(npc)
        {
            npc.OnCollision += new EventHandler<CollisionEventArgs>(npc_OnCollision);
        }

        void npc_OnCollision(object sender, CollisionEventArgs e)
        {
            if (e.Other is Actor)
                return;

            if (e.Direction == Direction.Left || e.Direction == Direction.Right)
            {
                _direction *= -1;
            }

            //Check if we reached end of a platform
            if (NPC.OnPlatform != null)
            {
                if (_direction.Equals(Vector2.UnitX) && Math.Abs(NPC.Bounds.Right - NPC.OnPlatform.Bounds.Right) < 5f)
                    _direction *= -1;
                else if (_direction.Equals(-Vector2.UnitX) && Math.Abs(NPC.Bounds.Left - NPC.OnPlatform.Bounds.Left) < 5f)
                    _direction *= -1;
            }
        }

        public override void Update(float dt)
        {
            base.Update(dt);

            if(NPC.IsOnGround)
                NPC.Movement = _direction;
        }
    }
}
